package com.ias.agdis_r.util;

import com.ias.agdis_r.R;
import com.ias.agdis_r.bean.task.Task;
import com.ias.agdis_r.bean.task.TaskField;
import com.ias.agdis_r.bean.task.TaskInfo;
import com.ias.agdis_r.bean.task.TaskProcess;
import com.ias.agdis_r.bean.task.TaskServiceLabel;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.ParameterModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class TaskUtil {

	private static int SORT_TYPE = -1;
	public static final int SORT_TIME_ASC = 0;       //按照时间升序排列
	public static final int SORT_TIME_DESC = 1;      //按照时间降序排列
	public static final int SORT_FLN_ASC = 2;        //按照航班号升序排列
	public static final int SORT_FLN_DESC = 3;       //按照航班号降序排列
	public static final int SORT_PSN_ASC = 4;        //按照机位升序排列
	public static final int SORT_PSN_DESC = 5;       //按照机位降序排列
	public static final int SORT_STATE_ASC = 6;      //按照状态升序排列
	public static final int SORT_STATE_DESC = 7;     //按照状态降序排列
	public static final int SORT_REG_ASC = 8;        //按照机号升序排列
	public static final int SORT_REG_DESC = 9;       //按照机号降序排列
	public static final int SORT_ACN_ASC = 10;          //按照机型升序排列
	public static final int SORT_ACN_DESC = 11;       //按照机型降序排列
	public static final int SORT_TYPE_ASC = 12;       //按照任务类型降序排列
	public static final int SORT_TYPE_DESC = 13;      //按照任务类型降序排列

	public static enum MonitorButtonStatus
	{
		NULL,MONITOR,SERVICE_LABEL
	}
	
	public final static int TASK_NULL = 0;              //无监控项和服务标注内容
	public final static int TASK_MONITOR = 1;           //有监控项
	public final static int TASK_SERVICE_LABEL = 2;     //无监控项有服务标注
	/**
	 * 进港航班，在航班号前面加"↓",离港航班则加"↑"
	 * 
	 * @param str
	 * @return
	 */ 
	public static String flightNum(String str, String AOD) {
		if (str.contains("↓") || str.contains("↑")) {
			return str;
		}

		if (AOD.equals("A")) {
			str = "↓" + str;// 进港航班
		} else {
			str = "↑" + str;// 离港航班
		}
		return str;

	}
	/**
	 * 获取显示的时间
	 * @param _sATO
	 * @param _sETO
	 * @param _sSTO
	 * @return
	 */
	public static String getFlightLatestTime(String _sATO, String _sETO, String _sSTO) {
		String sTime = "";
		if (S.isNotEmpty(_sATO)) {
			sTime = _sATO;
		} else if (S.isNotEmpty(_sETO)) {
			sTime = _sETO;
		} else if (S.isNotEmpty(_sSTO)) {
			sTime = _sSTO;
		}
		return sTime;
	}
	
	public static LinkedHashMap<String,TaskProcess> processSort(LinkedHashMap<String,TaskProcess> processMap)
	{
		LinkedHashMap<String,TaskProcess> sortProcessMap = new LinkedHashMap<String, TaskProcess>();
		int processMapSize = processMap.keySet().size();
		for(int i=0; i<processMapSize; i++)
		{
			TaskProcess process = null;
			Set<String> pidSet = processMap.keySet();
			for(String pid:pidSet)
			{
				if(process==null)
				{
					process = processMap.get(pid);
				}
				else
				{
					String pidx1 = process.getPIDX();
					String pidx2 = processMap.get(pid).getPIDX();
					if (Integer.parseInt(pidx1) > Integer.parseInt(pidx2)) {
						process = processMap.get(pid);
					}
				}
			}
			if(process!=null)
			{
				processMap.remove(process.getPCID());
				sortProcessMap.put(process.getPCID(), process);
			}
		}
		return sortProcessMap;
		
	}

	public static LinkedHashMap<String,TaskField> taskFieldSort(LinkedHashMap<String,TaskField> taskFieldMap)
	{
		if(taskFieldMap==null){
			return null;
		}
		LinkedHashMap<String,TaskField> sortTaskFieldMap = new LinkedHashMap<String, TaskField>();
		int taskFieldMapSize = taskFieldMap.keySet().size();
		for(int i=0; i<taskFieldMapSize; i++)
		{
			TaskField taskField = null;
			Set<String> fcodeSet = taskFieldMap.keySet();
			for(String fcode:fcodeSet)
			{
				if(taskField==null)
				{
					taskField = taskFieldMap.get(fcode);
				}
				else
				{
					String fidx1 = taskField.getFieldIndex();
					String fidx2 = taskFieldMap.get(fcode).getFieldIndex();
					if (Integer.parseInt(fidx1) > Integer.parseInt(fidx2)) {
						taskField = taskFieldMap.get(fcode);
					}
				}
			}
			if(taskField!=null)
			{
				taskFieldMap.remove(taskField.getFieldCode());
				sortTaskFieldMap.put(taskField.getFieldCode(), taskField);
			}
		}
		return sortTaskFieldMap;

	}
	
	/**
	 * 检查是否有监控项内容
	 * @param tnb
	 * @return
	 */
	public static MonitorButtonStatus checkTaskMonitor(String tnb)
	{
		Task task = DataManager.getInstance().getWorkTask(tnb);
		//如果任务不为空
		if(task!=null)
		{
			//判断是否有监控项
			HashMap<String, TaskProcess> processLabel = task.getProcessMap();
			Iterator<String>  iterator= processLabel.keySet().iterator();
			String key ="";
			while(iterator.hasNext())   {   			
	             key  =(String)iterator.next();                
	             TaskProcess taskProcess= task.getProcess(key);
	             //如果是监控项
	             if("N".equals(taskProcess.getIFSW()))
	             {
	            	 return MonitorButtonStatus.MONITOR;
	             }
			}
			
			//判断是否有服务标注
			if(task.getServiceLabelMap().size()!=0)
			{
				return MonitorButtonStatus.SERVICE_LABEL;
			}
		}
		return MonitorButtonStatus.NULL;
	}
	/**
	 * 检查通用任务是否有监控项内容
	 * @param tnb
	 * @return
	 */
	public static MonitorButtonStatus checkNFTaskMonitor(String tnb){
		Task task = DataManager.getInstance().getWorkNFTask(tnb);
		//如果任务不为空
		if(task!=null)
		{
			//判断是否有服务标注
			if(task.getServiceLabelMap().size()!=0)
			{
				for (TaskServiceLabel label : task.getServiceLabelMap().values()){
					if (label.getIsMark()){
						return MonitorButtonStatus.SERVICE_LABEL;
					}
				}
			}
		}
		return MonitorButtonStatus.NULL;
	}
	
	/**
	 * 判断任务是否存在下一任务节点
	 * @param task
	 * @return
	 */
	
	public static TaskProcess getNextTaskNode(Task task)
	{
		//下一任务节点
		TaskProcess nextProcess = null;
		//如果任务不为空，且任务的PID不为空
		if(task!=null&&S.isNotEmpty(task.getPID()))
		{
			HashMap<String, TaskProcess> processMap = task.getProcessMap();
			//当前任务进程节点
			TaskProcess myProcess = processMap.get(task.getPID());
			if (myProcess==null)
			{
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, DataBaseManager.getInstance().getContext().getString(R.string.processError), false);
				return null;
			}
			Iterator<String>  iterator= processMap.keySet().iterator();
			String key ="";
			while(iterator.hasNext())   {   
				
				//取最后面的key
		         key  =(String)iterator.next(); 
		         nextProcess = processMap.get(key);
				//如果当前的节点为取消或拒绝不处理
				if(nextProcess.getPCID().equals(MessageModel.TCXX)
						||nextProcess.getPCID().equals(MessageModel.TRJT)
						||nextProcess.getPCID().equals(MessageModel.T_ECXX)
						||nextProcess.getPCID().equals(MessageModel.T_ERJT)){
					nextProcess = null;
				}
		         //如果是需要显示的任务节点，且IDX大于当前IDX
				else if("Y".equals(nextProcess.getIFSW())&&Integer.valueOf(nextProcess.getPIDX())>Integer.valueOf(myProcess.getPIDX()))
		         {
		             break;
		         }
		         else
		         {
		        	 nextProcess = null;
		         }
		     }
		}
		return nextProcess;
	}
	
	/**
	 * 根据TNB获取对应工作任务的绑定车号
	 * @param tnb
	 * @return
	 */
	public static String getVNBbyTNB(String tnb)
	{
		String vnb = null;
		Task task = DataManager.getInstance().getWorkTask(tnb);
		if(task!=null)
		{
			TaskInfo taskInfo = task.getTaskInfo();
			if(taskInfo!=null)
			{
				vnb = taskInfo.getVNB();
			}
		}
		
		return vnb;
	}
	
	/**
	 * 检查是否有航班总结信息
	 * @return
	 */
	public static boolean checkSummary(String tnb,String pid)
	{
		Task task = DataManager.getInstance().getReceiveTask(tnb);
		if(task == null)
		{
			task = DataManager.getInstance().getWorkTask(tnb);
		}
		if(task!=null)
		{
			System.out.println("============================================pid1:"+pid);
			if(S.isEmpty(pid))
			{
				//如果PID没有内容，取下一个节点
				TaskProcess pN = TaskUtil.getNextTaskNode(task);
				if (pN !=null)
				{
					pid = pN.getPCID();
				}
			}
			System.out.println("============================================pid2:"+pid);
			if (S.isEmpty(pid)) {
				return false;
			}
			List<String> msgList = JavaBeanManager.getInstance().getSummaryTemplates().get(pid);
			if(msgList!=null)
			{
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 获取航班总结类别的名称
	 * @param type
	 * @return
	 */
	public static String getSumProjectName(String type)
	{
		String name = "";

		String[][] lockProjectList = ParameterModel.LOCKTYPENAMEMAP;
		for(String[] lockItem:lockProjectList)
		{
			if(S.valueOf(type).equals(lockItem[0]))
			{
				name = lockItem[1];
			}
		}
		return name;
	}

	/**
	 * 判断验证节点是否在当前任务节点前
	 * @param task
	 * @return
	 */
	public static boolean checkNodeBeforeCurrent(Task task,String checkpid){
		try {
			//下一任务节点
			TaskProcess myProcess = null;
			TaskProcess checkProcess = null;
			String myPid = task.getPID();
			if(task!=null&&S.isNotEmpty(myPid)){
				myProcess = task.getProcess(myPid);
				checkProcess = task.getProcess(checkpid);
				int mypIdx = Integer.parseInt(S.valueOf(myProcess.getPIDX()));
				int checkIdx = Integer.parseInt(S.valueOf(checkProcess.getPIDX()));
				if(checkIdx>mypIdx){
					return true;
				}
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static void shortServiceLabelMap(Task task) {
		if (task != null && "Y".equals(task.getEVENT()) && null != task.getServiceLabelMap()) {
			HashMap<String, TaskServiceLabel> oldMap = task.getServiceLabelMap();
			LinkedHashMap<String, TaskServiceLabel> newMap = new LinkedHashMap<String, TaskServiceLabel>();
			int midx = 1;
			for (int i = 0; i < oldMap.size(); i++) {
				Set<String> keySet = oldMap.keySet();
				for (String key : keySet) {
					if (S.valueOf(midx).equals(oldMap.get(key).getMIDX())) {
						newMap.put(key, oldMap.get(key));
						midx += 1;
						break;
					}
				}
			}
			for (String key : oldMap.keySet()) {
				TaskServiceLabel label = oldMap.get(key);
				if (label.getIsMark()){
					newMap.put(key, oldMap.get(key));
				}
			}
			task.setServiceLabelMap(newMap);
		}
	}

	/**
	 * 根据fke获取任务号
	 * @param fke
	 * @return
	 */
	public static List<String> getTnbByFke(String fke) {
		Set<String> taskNoSet = new TreeSet<>();
		// 根据航班唯一号fke，遍历任务得到任务号，如果有多个任务号，弹窗给出提示选择。
		LinkedHashMap<String, Task> workTaskList = DataManager.getInstance().getWorkTaskList();
		Iterator<String> iteratorWorkTask = workTaskList.keySet().iterator();
		while (iteratorWorkTask.hasNext()) {
			String next = iteratorWorkTask.next();
			Task workTask = workTaskList.get(next);
			if (fke.equals(workTask.getTaskInfo().getFKE())) {
				taskNoSet.add(workTask.getTNB());
			}
		}
		LinkedHashMap<String, Task> receiveTaskList = DataManager.getInstance().getReceiveTaskList();
		Iterator<String> iteratorReceiveTask = receiveTaskList.keySet().iterator();
		while (iteratorReceiveTask.hasNext()) {
			String next = iteratorReceiveTask.next();
			Task workTask = receiveTaskList.get(next);
			if (fke.equals(workTask.getTaskInfo().getFKE())) {
				taskNoSet.add(workTask.getTNB());
			}
		}
		List<String> list = new ArrayList<>();
		list.addAll(taskNoSet);
		return list;
	}
}
